<?php
// +----------------------------------------------------------------------
// | When work is a pleasure, life is a joy!
// +----------------------------------------------------------------------
// | User: ShouKun Liu  |  Email:24147287@qq.com  | Time:2016/12/11 14:06
// +----------------------------------------------------------------------
// | TITLE:订单控制器
// +----------------------------------------------------------------------
namespace Qwadmin\Controller;

use Common\Model\MemberModel;
use Common\Model\OrderModel;
use Think\Page;
use Vendor\PHPExcel;


/**
 * Class OrderController
 * @package Qwadmin\Controller
 */
class OrderController extends ComController
{
    const ROOT_ROLE = 1;
    const  FIRST_ROLE = 8;//第一客服处理
    const  SECOND_ROLE = 9;//第二客服处理

    public static $userRule;


    public static $roleStatus = array(
        self::ROOT_ROLE => array(OrderModel::ACTIVATE_STATUS, OrderModel::QUERY_STATUS, OrderModel::SET_STATUS),
        self::FIRST_ROLE => array(OrderModel::ACTIVATE_STATUS, OrderModel::SET_STATUS),//前端客服
        self::SECOND_ROLE => array(OrderModel::ACTIVATE_STATUS, OrderModel::QUERY_STATUS,OrderModel::SET_STATUS),//安装客服
        'all' => array(OrderModel::ADD_STATUS, OrderModel::CLOSE_STATUS, OrderModel::OTHER_STATUS,OrderModel::ACCEPT_STATUS)//所有权限
    );
    /**
     * 状态对应的用户存储字段
     * @var array
     */
    public static $statusField = array(
        OrderModel::ADD_STATUS => 'dispose_user',
        OrderModel::ACTIVATE_STATUS => 'dispose_user',
        OrderModel::QUERY_STATUS => 'dispose_user2',
        OrderModel::CLOSE_STATUS => 'dispose_user',
        OrderModel::OTHER_STATUS => 'dispose_user',
        OrderModel::SET_STATUS => 'dispose_user',

    );
    public static $roleField = array(
        self::ROOT_ROLE => 'dispose_user',//第一客服存储字段
        self::FIRST_ROLE => 'dispose_user',//第一客服存储字段
        self::SECOND_ROLE => 'dispose_user2',//第二客服存储字段

    );

    public function _initialize()
    {
        parent::_initialize();
        $this->assign('FIRST_ROLE', self::FIRST_ROLE);//第一客服处理
        $this->assign('SECOND_ROLE', self::SECOND_ROLE);//第二客服处理
        $this->assign('ROOT_ROLE', self::ROOT_ROLE);//第二客服处理
        $this->assign('roleId', $this->roleId);//角色ID
        self::$userRule = $this->getUserRule();
        $this->assign('ruleList', $this->userRule);
    }

    /**
     * 获取权限
     * @return array
     */
    public function getUserRule()
    {
        $MemberModel = new  MemberModel();
        $roleId = $MemberModel->getUserGroupID($this->USER['uid']);
        return array_merge(self::$roleStatus[$roleId], self::$roleStatus['all']);

    }

    public function lists()
    {

        //获取通知
         $this->assign('message',S('message'));

        $where = I('');
        if (!empty($where['order_no'])) $wheres['order_no'] = array('like', "%$where[order_no]%");
        if (!empty($where['source'])) $wheres['source'] = array('like', "%$where[source]%");
        if (!empty($where['game_user'])) $wheres['game_user'] = array('like', "%$where[game_user]%");
        if (!empty($where['mobile'])) $wheres['mobile'] = array('like', "%$where[mobile]%");
        if (!empty($wheres)) {
            $wheres['_logic'] = 'and';
            $map['_complex'] = $wheres;
        }
        if (!empty($where['is_aftersale'])) $map['is_aftersale'] = $where['is_aftersale'];
        if (!empty($where['status'])) $map['status'] = $where['status'];
        if (!empty($where['dispose_user'])) $map['dispose_user'] = $where['dispose_user'];
        if (!empty($where['dispose_user2'])) $map['dispose_user2'] = $where['dispose_user2'];

        if(empty($map['_complex'])){
            $time = I('time');
            $start = (empty($time)) ? date('Y-m-d 00:00:00') : $time;
            $end = (empty($time)) ? date('Y-m-d 00:00:00') : $time;
            $start = date('Y-m-d 00:00:00', strtotime($start));
            $end = date('Y-m-d 23:59:59', strtotime($end));
            $map['create_date'] = array(array('gt', $start), array('lt', $end), 'and');
        }

        $pageSize = I('pageSize', '20');
        $OrderModel = new OrderModel();
        $count = $OrderModel->where($map)->count();

        if (I('exportOrder', '')) {
            $orders = $OrderModel->where($map)->order('id desc')
                ->select();
            $this->exportOrder($time . "的订单", $orders);

        }

        $Page = new Page($count, $pageSize);
        $orderList =
            $OrderModel
                ->where($map)
                ->order('status asc, id desc')
                ->limit($Page->firstRow, $Page->listRows)
                ->select();
        $this->assign('page', $Page->show());
        $this->assign('list', $orderList);
        $this->assign('member', self::getMember());
        $this->assign('statusList', self::ruleStatusList());
        $this->assign('closeStatus', OrderModel::CLOSE_STATUS);
        $this->assign('user', $this->USER['user']);
        $this->display();

    }

    public static function ruleStatusList()
    {
        $statusList = OrderModel::statusList();
        foreach (self::$userRule as $v) {
            $arr[$v] = $statusList[$v];
        }
        return $arr;


    }

    /**
     * 获取用户列表
     * @return mixed
     */
    public static function getMember()
    {
        return M('member')->select();
    }

    public function editOrder()
    {
        $this->assign('statusList', self::ruleStatusList());
        $id = I('id');

        $OrderModel = new OrderModel();
        $orderInfo = $OrderModel->where(array('id' => $id))->find();
        if ($orderInfo == false) $this->error('错误');
        //不是超级管理员进行验证
        if ($this->roleId != self::ROOT_ROLE) {
            if (!empty($orderInfo[self::$statusField[OrderModel::ADD_STATUS]]) && $orderInfo[self::$statusField[OrderModel::ADD_STATUS]] != $this->USER['user']) {
                $this->error('该单已其他客服处理');
            }
        }
        if (IS_POST) {
            $data = I('');
            unset($data['id']);
            $data['dispose_date'] = date('Y-m-d H:i:s');
            if ($this->roleId != self::SECOND_ROLE)
            $data[self::$roleField[$this->roleId]] = $this->USER['user'];

            ($OrderModel->where(array('id' => $id))->save($data)) ? $this->success('修改成功', U('editOrder', array('id' => $id))) : $this->error('修改失败');


        } else {
            $this->assign('orderInfo', $orderInfo);
            $this->display();
        }


    }

    public function changeOrderStatus()
    {
        //获取用户角色ID
        $MemberModel = new  MemberModel();
        $roleId = $MemberModel->getUserGroupID($this->USER['uid']);

        $id = I('id');
        $status = I('status', '');
        $OrderModel = new OrderModel();
        //验证权限
        if (!in_array($status, $this->getUserRule())) {
            $this->error('请另外一个客服处理!');
        }

            $order = $OrderModel->where(array('id' => $id))->find();

            if (!empty($order[self::$statusField[$status]]) && $order[self::$statusField[$status]] != $this->USER['user']) {
                $this->error('该单已其他客服处理');
            }

        ($OrderModel->changeOrderStatus($id, $status, $this->USER['user'],self::$statusField[$status])) ? $this->success('修改成功', U('lists')) : $this->error('修改失败');
    }

    /**
     * 导出订单
     * @param $title
     * @param $orderList
     */
    public function exportOrder($title, $orderList)
    {
        $xlsName = $title;
        $xlsCell = array(
            array('order_no', '工单号'),
            array('game_user', '客户账号'),
            array('source', '订单来源'),
            array('mobile', '手机'),
            array('create_date', '创建时间'),
            array('user_remark', '用户备注'),
            array('dispose_user', '客服一'),
            array('dispose_user2', '客服二'),
            array('dispose_date', '最后处理时间'),
            array('status', '状态'),
            array('is_aftersale', '是否售后'),
            array('dispose_remark', '备注'),
        );
        foreach ($orderList as $k => $v) {
            $orderList[$k]['status'] = os_to_str($v['status'], 'title');
            $orderList[$k]['is_aftersale'] = sf_to_str($v['is_aftersale']);
        }
        exportExcel($xlsName, $xlsCell, $orderList, $xlsName);
    }


    public function addMessage()
    {
        if (IS_POST){
          S('message',I('content'),0);
            $this->success('通知成功',U('addMessage'));
        }else{
            $message =S('message');
            $this->assign('message',$message);
            $this->display();
        }
    }
}